<?php

class DBHelper {

	protected $dbType = "mysql";
	protected $host = "localhost";
	protected $dbName = "imacoder";
	protected $username = "root";
	protected $password = "root";
	protected $connection = null;

	public function __construct(){
		try{
			$dsn = "$this->dbType:host=$this->host;dbname=$this->dbName";
			$this->connection = new PDO($dsn, $this->username, $this->password);
		}catch(PDOException $e){
			die ("Error!: " . $e->getMessage() . "<br/>");
		}
	}

	// 初始化一些sql语句
	protected $sql_select_columns;
	protected $sql_from;
	protected $sql_where;

	protected function quote($string){
		return $this->connection->quote($string);
	}

	public function select($columns = '*'){
		$this->sql_select_columns = $columns;
		$this->sql_from_tableName = '';
		$this->sql_where = '';
		return $this;
	}

	public function where($conditons){
		$this->sql_where .= " WHERE $conditons";
		return $this;
	}

	public function from($tableName = ''){
		$this->sql_from_tableName = $tableName; 
		return $this;
	}

	protected function buildSql(){
		return "SELECT " . $this->sql_select_columns . " FROM " . $this->sql_from_tableName . $this->sql_where;
	}

	public function query($sqlString){
		if($sqlString == '')
			return $this->connection->query($this->buildSql())->fetchAll();
		else
			return $this->connection->query($sqlString)->fetchAll();
	}

	public function insert($tableName, $data){
		if(is_array($data) && !empty($data)){
			$columns = implode(',', array_keys($records[0]));
			$sql = "INSERT INTO $tableName ($columns) VALUES ";
			foreach ($data as $record) {
				foreach ($record as $key => $value) {
					$record[$key] = $this->quote($value);
				}
				$sql .= "(" . implode(',', array_values($record)) . "),";
			}
			$sql = substr($sql, 0, -1);
			$num = $this->connection->exec($sql) or die(print_r($this->connection->errorInfo(), true));
			return $num;
		}else{
			return false;
		}
	}

	public function delete($sqlString){

	}

	public function update($sqlString){

	}
}